# _*_ coding: utf-8 _*_
from odoo import models, fields, _
from odoo.exceptions import UserError


class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    def button_confirm(self):
        for order in self:
            if any(line.product_purchase_limit_control and line.product_qty > line.product_purchase_limit
                   for line in order.order_line):
                raise UserError(_("Product quantity must less then product purchase limit."))
        super(PurchaseOrder, self).button_confirm()


class PurchaseOrderLine(models.Model):
    _inherit = "purchase.order.line"

    product_purchase_limit_control = fields.Boolean(string="Template Purchase Limit Control",
                                                    related="product_id.product_purchase_limit_control")
    product_purchase_limit = fields.Float(string="Template Limit",
                                          related="product_id.product_purchase_limit", readonly=True)
